package com.nbsaas.boot.config.ext.resource;

import com.nbsaas.boot.config.data.entity.UserConfig;
import com.nbsaas.boot.config.data.repository.UserConfigRepository;
import com.nbsaas.boot.config.ext.apis.UserConfigExtApi;
import com.nbsaas.boot.config.ext.domain.request.UserConfigExtRequest;
import com.nbsaas.boot.rest.response.ResponseObject;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class UserConfigExtResource implements UserConfigExtApi {

    @Resource
    private UserConfigRepository userConfigRepository;

    public String data(UserConfigExtRequest request) {
        if (request == null) {
            return null;
        }
        if (request.getKey() == null) {
            return null;
        }
        UserConfig temp = userConfigRepository.findByClassNameAndUserId(request.getKey(), request.getUserId());

        if (temp == null) {
            temp = new UserConfig();
            temp.setClassName(request.getKey());
            temp.setConfigData(request.getValue());
            temp.setUserId(request.getUserId());
            userConfigRepository.save(temp);
            return request.getValue();
        }
        if (StringUtils.hasText(request.getValue())){
            temp.setConfigData(request.getValue());
            temp.setLastDate(new Date());
        }
        return temp.getConfigData();
    }

    @Transactional
    @Override
    public ResponseObject<String> key(UserConfigExtRequest request) {
        ResponseObject<String> result=new ResponseObject<>();
        if (request == null) {
            result.setCode(501);
            result.setMsg("空数据");
            return result;
        }
        if (request.getKey() == null) {
            result.setCode(502);
            result.setMsg("无效的key");
            return result;
        }
        if (request.getUserId() == null) {
            result.setCode(502);
            result.setMsg("无效的key");
            return result;
        }
        String temp = data(request);
        result.setData( temp);
        return result;
    }

    @Transactional
    @Override
    public ResponseObject<String> value(UserConfigExtRequest request) {
        return key( request);
    }
}
